import * as THREE from "three";
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";

export function initThree(x = 0, y = 20, z = 100) {

  this.scene = new THREE.Scene()

  // 添加坐标辅助器
  // 用于简单模拟3个坐标轴的对象.
  // 红色代表 X 轴. 绿色代表 Y 轴. 蓝色代表 Z 轴.
  const axesHelper = new THREE.AxesHelper(50);
  this.scene.add(axesHelper);


  // this.scene.background = new THREE.Color('#eee')
  const canvas = document.querySelector('#three')

  // 抗锯齿（Anti-Aliasing）：启用抗锯齿可以减少模型显示时的锯齿和模糊。在创建渲染器时，将 antialias 参数设置为 true。
  this.renderer = new THREE.WebGLRenderer({canvas, antialias: true})

  // 将输出canvas的大小调整为(width, height)并考虑设备像素比，
  // 且将视口从(0, 0)开始调整到适合大小 将updateStyle设置为false以阻止对canvas的样式做任何改变。
  // 分辨率设置：确保将渲染器的分辨率设置为适当的值。较高的分辨率可以提高图像的清晰度。例如：
  this.renderer.setSize(window.innerWidth, window.innerHeight);

  // 增加像素比率：通过使用 setPixelRatio() 方法增加像素比率，可以提高模型的清晰度
  this.renderer.setPixelRatio(window.devicePixelRatio);





  this.camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  )

  this.camera.position.set(x, y, z);

  this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement)


  //controls.update() must be called after any manual changes to the camera's transform

  this.orbitControls.update();
}

export function initCameraMoveFunction() {


  document.addEventListener('keydown', event=>{
    var keyCode = event.keyCode;

    if (keyCode === 87) { // W键
      this.moveForward = true;
    } else if (keyCode === 83) { // S键
      this.moveBackward = true;
    } else if (keyCode === 65) { // A键
      this.moveLeft = true;
    } else if (keyCode === 68) { // D键
      this.moveRight = true;
    }
  });

  document.addEventListener('keyup',  event=> {
    var keyCode = event.keyCode;

    if (keyCode === 87) { // W键
      this.moveForward = false;
    } else if (keyCode === 83) { // S键
      this.moveBackward = false;
    } else if (keyCode === 65) { // A键
      this.moveLeft = false;
    } else if (keyCode === 68) { // D键
      this.moveRight = false;
    }
  });

}

export function updateCameraPosition() {
  if (this.moveForward) {

    this.camera.position.z -= 0.1;
  }
  if (this.moveBackward) {
    this.camera.position.z += 0.1;
  }
  if (this.moveLeft) {
    this.camera.position.x -= 0.1;
  }
  if (this.moveRight) {
    this.camera.position.x += 0.1;
  }
}
